// pages/downloadPic/downloadPic.js
var app = getApp()
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    picInfo: [],
    isbuy: false,
    compet_id: '',
    free: false,
    showLoading: false,
    imgMaskWidth:"",
    imgMaskHeight:""
  },
  // 点击购买按钮
  buyPic() {
    let that = this
    let photo_id = that.data.picInfo[0].id
    let price = parseFloat(that.data.picInfo[0].price)
    let token = wx.getStorageSync('token')
    let compet_id = this.data.compet_id
    let type = wx.getStorageSync('type')
    // ||type==undefined||type==''
    if (token == '') {
      Toast.fail('请先登录')
      setTimeout(() => {
        wx.switchTab({
          url: '/pages/personal/personal',
        })
      }, 1500)
      return
    }
    let params = {
      price,
      photo_id,
      token,
      compet_id
    }
    wx.request({
      url: app.globalData.host + 'Competition/wxpay',
      data: params,
      method: 'GET',
      success(res) {
        if (res.data.code == 2000) {
          let {
            nonceStr,
            package: package1,
            signType,
            paySign,
            timeStamp
          } = res.data.data
          if (nonceStr == undefined) {
            wx.showLoading({
              title: '请登录后再支付',
            })
            setTimeout(() => {
              wx.switchTab({
                url: '/pages/personal/personal'
              })
            }, 1500)
            return
          }
          wx.requestPayment({
            nonceStr,
            package: package1,
            paySign,
            signType,
            timeStamp,
            success: (suc) => {
              wx.showToast({
                title: '支付成功',
              })
              console.log(suc)
              that.getMyPic(photo_id)
              // setTimeout(() => {
              //   wx.navigateTo({
              //     url: '/pages/videoDetail/videoDetail?file_id='+that.data.file_id
              //   })
              // }, 1000)
            },
            fail(error) {
              wx.showToast({
                title: '支付失败',
                icon: 'none'
              })
              console.log(error)
              that.getMyPic(photo_id)
              // setTimeout(() => {
              //   wx.navigateTo({
              //     url: '/pages/videoDetail/videoDetail?file_id='+that.data.file_id
              //   })
              // }, 1000)
            }
          })
        } else {
          console.log(res)
          Toast.fail('出了一些问题,请重新登录试试,状态码:' + res.statusCode)
          setTimeout(() => {
            wx.switchTab({
              url: '/pages/personal/personal'
            })
          }, 4000)
        }
      },
      fail(err) {
        console.log(err)
        Toast.fail('出了一些问题,请重新登录试试,状态码:' + res.statusCode)
        setTimeout(() => {
          wx.switchTab({
            url: '/pages/personal/personal'
          })
        }, 4000)
      }
    })

  },
  test() {
    wx.navigateTo({
      url: '/test/pages/testpage/testpage',
    })
  },
  // 点击下载按钮
  downloadPic() {
    const that = this
    that.setData({
      showLoading: true
    })
    if (that.data.imgInfo) {
      var url = that.data.imgInfo.logo
      that.setData({
        url
      })
    } else {
      var url = that.data.picInfo[0].logo_zip
      that.setData({
        url
      })
    }
    wx.downloadFile({
      url: that.data.url, //图片URL
      success: function (res) {
        // 只要服务器有响应数据，就会把响应内容写入文件并进入 success 回调，业务需要自行判断是否下载到了想要的内容
        console.log(res);
        if (res.statusCode === 200) {
          wx.saveImageToPhotosAlbum({
            filePath: res.tempFilePath,
            success: function (data) {
              console.log(data);
              wx.showToast({
                title: '下载成功',
                icon: 'none',
                duration: 2000
              })
              that.setData({
                showLoading: false
              })
            },
            fail: function (err) {
              console.log(err);
              if (err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
                console.log("用户一开始拒绝了，我们想再次发起授权")
                wx.showToast({
                  title: '下载已取消',
                  icon: 'none',
                  duration: 3000
                })
                that.setData({
                  showLoading: false
                })
                wx.openSetting({
                  success(settingdata) {
                    console.log(settingdata)
                    if (settingdata.authSetting['scope.writePhotosAlbum']) {
                      console.log('获取权限成功，给出再次点击图片保存到相册的提示。')
                    } else {
                      console.log('获取权限失败，给出不给权限就无法正常使用的提示')
                    }
                  }
                })
              }
            }
          })
        }
      },
      complete: function (res) {

      },
      fail: function (res) {
        console.log(res)
        wx.showToast({
          title: '下载失败,原因:' + res.errMsg,
          icon: 'none',
          duration: 3000
        })
        that.setData({
          showLoading: false
        })
      },
      timeout: function (res) {
        wx.showToast({
          title: '下载超时',
        })
      }
    })
  },
  // 获取已购买图片信息
  getMyPic(id) {
    const that = this
    let token = wx.getStorageSync('token')
    wx.request({
      url: app.globalData.host + 'Competition/my_photo',
      data: {
        id,
        token
      },
      method: 'POST',
      success(res) {
        if (res.data.code == 2000) {
          that.setData({
            isbuy: true,
            imgInfo: res.data.data
          })
        } else {
          that.setData({
            isbuy: false
          })
        }
      }
    })
  },
  imgLoad() {
    const query = wx.createSelectorQuery()
    query.select('.photo').boundingClientRect();
    query.exec((res) => {
      this.setData({
        imgMaskHeight:res[0].height,
        imgMaskWidth:res[0].width,
      })
    })
  },
  // 获取图片信息
  getPicInfo(id) {
    const that = this
    let token = wx.getStorageSync('token')
    wx.request({
      url: app.globalData.host + 'Competition/photo',
      method: 'POST',
      data: {
        id,
        token
      },
      success(res) {
        if (res.data.code == 2000) {
          let data = res.data.data
          if (data.is_pay == 1) {
            console.log('已购买')
            that.getMyPic()
            return
          }
          that.setData({
            picInfo: data
          })
          console.log(data)
          if (data[0].price == '0' || data[0].price == null || data[0].price == undefined || data[0].price == '') {
            that.setData({
              free: true
            })
          }
        } else {
          Toast.fail(res.data.msg)
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const that = this
    let id = parseInt(options.id.split('-')[3])
    that.getMyPic(id)
    that.setData({
      id,
      compet_id: options.compet_id
    })
    that.getPicInfo(id)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})